<template>
  <el-dialog
      :title="title?title:isUpdate?'修改':'新增'"
      :visible="show"
      @close="openSelf(false)"
      :width="width">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item v-for="k in Object.keys(formConfig)" :key="k" :label="formConfig[k].label" :rules="formConfig[k].rules" :prop="k">
        <slot :name="'form-item'" :field="k" :value="form[k]" :form="form"></slot>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="tool-bar">
        <el-button type="danger" @click="openSelf(false)">关闭</el-button>
        <el-button type="primary" @click="saveFun">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import {copy} from '../utils/obj-utils'

export default {
  name : 'AForm',
  model:{
    event:'showOrClose',
    prop:'show'
  },
  props:{
    show:{
      type:Boolean,
      default:false
    },
    title:{
      type:String,
      default : undefined
    },
    width:{
      type:String,
      default : '70%'
    },
    initForm:{
      type:Object,
      default:undefined
    },
    formConfig:Object
  },
  data(){
    return{
      form:{},
      isUpdate:false,
    }
  },
  methods:{
    //打开或者关闭表达函数
    openSelf(formState){
      console.log("表单的状态:",formState?'打开':'关闭')
      this.$emit('showOrClose',formState)
    },
    saveFun(){
      this.$refs.form.validate((validated)=>{
        if ( validated ){
          this.$emit('save',this.form)
        }
      })
    }
  },
  watch:{
    initForm:{
      deep:true,
      immediate:true,
      handler:function ( newObj ){
        console.log("监听到新的initForm值：",newObj)
        if ( newObj ){
          this.form= newObj
          this.isUpdate=true
        }else {
          this.form={}
          this.isUpdate=false
        }
      }
    }
  }
}
</script>

<style scoped>
.tool-bar{
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>